<template>
  <div class="home-container">
    <el-container>
      <!-- 头部区域 -->
      <el-header>
        <h2 class="header-title">购物管理系统</h2>
      </el-header>

      <el-container>
        <!-- 侧边栏菜单 -->
        <el-aside width="200px">
          <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical-demo"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/adminhomeproduct">
              <i class="el-icon-goods"></i>
              <span>商品管理</span>
            </el-menu-item>
            <el-menu-item index="/adminhomeorder">
              <i class="el-icon-s-order"></i>
              <span>订单管理</span>
            </el-menu-item>
            <el-menu-item index="/adminhomeuser">
              <i class="el-icon-user"></i>
              <span>用户管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        <!-- 主内容区域 -->
        <el-main>
          <div class="main-content">
            <div class="toolbar">
              <!-- <el-input
                v-model="search"
                placeholder="搜索商品..."
                class="search-bar"
              /> -->
              <el-button type="primary" @click="showDialog">新增商品</el-button>
            </div>
            <!-- 弹窗组件 -->
            <ProductDialog
              :visible.sync="isDialogVisible"
              @submit="addProduct"
            />
            <ProductUpdateDialog
              :visible.sync="isUpdateDialogVisible"
              :productData="updateproduct"
              @submit="updateProduct"
            />

            <el-table
              ref="multipleTable"
              :data="productData.data"
              tooltip-effect="dark"
              style="width: 100%; font-size: 20px"
            >
              <el-table-column width="40"></el-table-column>
              <el-table-column
                prop="id"
                label="商品id"
                width="100"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column label="商品图片" width="200">
                <template #default="scope">
                  <img
                    :src="scope.row.image"
                    alt="SmallImage"
                    class="resized-image"
                  />
                </template>
              </el-table-column>

              <el-table-column
                prop="name"
                label="商品名称"
                width="250"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="description"
                label="商品描述"
                width="300"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="type"
                label="商品种类"
                width="100"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="price"
                label="单价"
                width="100"
              ></el-table-column>
              <el-table-column
                prop="stock"
                label="库存"
                width="100"
              ></el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" @click="showUpdateDialog(scope.row)">
                    编辑
                  </el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deleteProduct(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import ProductDialog from '@/components/ProductDialog.vue'
import ProductUpdateDialog from '@/components/ProductUpdateDialog.vue'
export default {
  name: 'AdminHomeProduct',
  components: {
    ProductDialog,
    ProductUpdateDialog,
  },
  data() {
    return {
      activeMenu: '/adminhomeproduct', // 默认选中的菜单项
      search: '', // 搜索框的内容
      productData: {}, // 商品数据
      newproduct: {
        name: '',
        description: '',
        type: '',
        image: '',
        price: '',
        stock: '',
      },
      updateproduct: {},
      isDialogVisible: false, // 控制对话框显示状态
      isUpdateDialogVisible: false, // 控制对话框显示状态
    }
  },
  mounted() {
    this.getProductData()
  },
  methods: {
    // 显示弹窗
    showDialog() {
      this.isDialogVisible = true
    },
    showUpdateDialog(product) {
      this.updateproduct = product
      this.isUpdateDialogVisible = true
    },
    handleMenuSelect(index) {
      console.log(`选中菜单项: ${index}`)
      this.activeMenu = index
      // 跳转到对应的路由路径
      this.$router.push(index).catch((err) => {
        // 捕获错误，避免重复点击报错
        if (err.name !== 'NavigationDuplicated') {
          console.error(err)
        }
      })
    },
    //添加商品
    async addProduct(product) {
      console.log('添加新商品')
      console.log(product)
      try {
        const token = localStorage.getItem('jwtToken') // 获取存储的 token
        const response = await this.$http.post(
          '/api/adminhome/add',
          {
            name: product.name,
            description: product.description,
            type: product.type,
            image: product.image,
            price: product.price,
            stock: product.stock,
          },
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        )
        if (response.data.code === 1) {
          this.$message({
            type: 'success',
            message: '商品已添加: ',
          })
          this.getProductData() // 重新获取商品数据，刷新页面
        }
      } catch {
        console.log('添加失败')
      }
    },
    //编辑商品
    async updateProduct(product) {
      console.log('编辑商品', product)
      try {
        const token = localStorage.getItem('jwtToken') // 获取存储的 token
        const response = await this.$http.post(
          '/api/adminhome/update',
          {
            id: product.id,
            name: product.name,
            description: product.description,
            type: product.type,
            image: product.image,
            price: product.price,
            stock: product.stock,
          },
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        )
        if (response.data.code === 1) {
          this.$message({
            type: 'success',
            message: '商品已修改: ',
          })
          this.getProductData() // 重新获取商品数据，刷新页面
        }
      } catch {
        console.log('修改失败')
      }
    },
    //删除商品
    async deleteProduct(product) {
      console.log('删除商品', product)
      try {
        const token = localStorage.getItem('jwtToken') // 获取存储的 token
        const response = await this.$http.delete(
          '/api/adminhome/' + product.id,
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        )
        if (response.data.code === 1) {
          this.getProductData() // 重新获取商品数据，刷新页面
        }
      } catch (error) {
        console.error('删除失败', error)
      }
    },
    //获取产品数据
    getProductData() {
      const token = localStorage.getItem('jwtToken') // 获取存储的 token

      this.$http
        .get('/api/home/product', {
          headers: {
            Authorization: `Bearer ${token}`, // 使用 Bearer 方案
          },
        })
        .then((res) => {
          this.productData = res.data
          console.log(this.productData.data)
        })
        .catch((err) => {
          console.log(err)
        })
    },
  },
}
</script>

<style scoped>
.header-title {
  padding-left: 200px;
}
.home-container {
  margin: 20px;
}

.main-content {
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-bar {
  width: 300px;
}
</style>
